﻿document.write("<script type='text/javascript' src='../Scripts/alert/ymPrompt.js'></script>");
document.write("<link rel='stylesheet' href='../Scripts/alert/skin/qq/ymPrompt.css' type='text/css' />");
var pageIndex = 1;
var total = 0;
var pageSize = 10;
var pageCount = 0;
var queryBuilder, ashxParam, columnInfo, addPage, editPage, detailPage;
var selectRows = new Array();
var SubmitFlag = false;
var columnInfo;
var _isShowCheckBox;
var _fnDoubleClick;
var _isClientColumns = false;
var _colorColumnIndex=6;
//判断浏览器
var userAgent = navigator.userAgent.toLowerCase();
var browser = {
    version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
    safari: /webkit/.test(userAgent),
    opera: /opera/.test(userAgent),
    msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};

$(document).ready(function () {
    //禁用右键
    /*  $(document).bind("contextmenu", function (e) {
    return false;
    });
    */
    //设置单条记录的checkbox单击事件
    $("#contentTable").on("click", "input[name='childCheckbox']", function (event) {
        var recordId = $(this).parent().parent().attr("id");
        if (browser.msie)
            recordId = $(this).parent().parent().parent().attr("id");
        if ($(this).prop("checked") == true) {
            $(this).prop("checked", true);
            selectRows.push(recordId);
        }
        else {
            $(this).prop("checked", false);
            if ($.inArray(recordId, selectRows) != -1)
                selectRows.splice($.inArray(recordId, selectRows), 1);

        }
    });

    //checkbox全选
    $("#contentTable").on("click", "input[name='headerCheckbox']", function (event) {

        if ($(this).is(':checked')) {
            $("#contentTable input[name='childCheckbox']").prop("checked", true);
        } else {
            $("#contentTable input[name='childCheckbox']").prop("checked", false);
        }
        var ifChecked = $(this).prop("checked");
        $("#contentTable input[name='childCheckbox']").each(function (i, n) {

            var recordId = $(this).parent().parent().attr("id"); //获取当前主键
            if (browser.msie)
                recordId = $(this).parent().parent().parent().attr("id");
            if (ifChecked == false) {
                if ($.inArray(recordId, selectRows) != -1)
                    selectRows.splice($.inArray(recordId, selectRows), 1);
            }
            else {
                if ($.inArray(recordId, selectRows) == -1)
                    selectRows.push(recordId);
            }
        });
    });
});


function initNewGrid(queryBuilderParam, ashxParamParam, addPageParam, editPageParam, detailPageParam, isShowCheckBox, fnDoubleClick, columnInfoParam,colorColumnIndex) {
    queryBuilder = queryBuilderParam;
    ashxParam = ashxParamParam;
    columnInfo = columnInfoParam;
    addPage = addPageParam;
    editPage = editPageParam;
    detailPage = detailPageParam;
    pageSize = ashxParam.pageSize;
    _isShowCheckBox = isShowCheckBox;
    _fnDoubleClick = fnDoubleClick;
    _colorColumnIndex = colorColumnIndex;
    if (columnInfo != null) {
        _isClientColumns = true;
    }
    //    if (columnInfo != null) {
    //        $("#contentTable").empty();
    //        //初始化表头部分
    //        var header = "";
    //        header = "<tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
    //        if (browser.msie)
    //            header = "<tbody><tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
    //        for (var i = 0; i < columnInfo.length; i++) {
    //            if (columnInfo[i].width != undefined)
    //                header += "<td class=\"headerTd\" width=\"" + columnInfo[i].width + "\">" + columnInfo[i].columnText + "</td>";
    //            else
    //                header += "<td class=\"headerTd\">" + columnInfo[i].columnText + "</td>";

    //        }
    //        header += "</tr>"; //<td width=\"150px\" class=\"headerTd\">基本操作</td>
    //        if (browser.msie)
    //            header += "</body>";
    //        $("#contentTable").append(header);

    //    }
    pageClick(isShowCheckBox, fnDoubleClick, colorColumnIndex);
    bindPageButton(isShowCheckBox, fnDoubleClick);


    $("#imgCreate").unbind("click");
    $("#imgCreate").click(function () {
        tb_show(addPageParam.title, addPageParam.url + "?keepThis=true&TB_iframe=true&height=" + addPageParam.height + "&width=" + addPageParam.width, false);
    });
    $("#imgUpdate").unbind("click");
    $("#imgUpdate").click(function () {
        popUpEditPage(editPage);
    });
    $("#imgDelete").unbind("click");
    $("#imgDelete").click(function () {
        deleteRecord(ashxParam);
    });


}

var highlightcolor = '#c1ebff';
//此处clickcolor只能用win系统颜色代码才能成功,如果用#xxxxxx的代码就不行,还没搞清楚为什么:(
var clickcolor = '#51b2f6';
//鼠标移动
function changeto() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (cs[1].style.backgroundColor != highlightcolor && source.id != "nc" && cs[1].style.backgroundColor != clickcolor)
        for (i = 0; i < 1; i++) {
            cs[i].style.backgroundColor = highlightcolor;
        }
}
//移动变色 
function changeback() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (event.fromElement.contains(event.toElement) || source.contains(event.toElement) || source.id == "nc")
        return
    if (event.toElement != source && cs[1].style.backgroundColor != clickcolor)
        for (i = 0; i < 1; i++) {
            cs[i].style.backgroundColor = "";
        }
}
//比如说加单击事件
function clickto() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (cs[1].style.backgroundColor != clickcolor && source.id != "nc")
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = clickcolor;
        }
    else
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = "";
        }
}
function pageClick(isShowCheckBox, fnDoubleClick, colorColumnIndex) {
    if (isShowCheckBox == undefined) {
        isShowCheckBox = true;
    }
    selectRows = []; //清空选中项
    //alert(colorColumnIndex);
    if (ashxParam.action == null || ashxParam.action == undefined)
        ashxParam.action = "04";
    var submitData = { "action": ashxParam.action, "pageSize": pageSize, "pageIndex": pageIndex };
    imgLoader = new Image(); // preload image
    imgLoader.src = "../images/loadingAnimation.gif";
    $("body").append("<div id='TB_load'><img src='" + imgLoader.src + "' /></div>"); //add loader to the page
    $('#TB_load').show(); //show loader

    if (ashxParam.url == null || ashxParam.url == "" || ashxParam.url == undefined) {
        $("#TB_load").remove();
        window.parent.tb_remove();
        return;
    }

    //将查询条件和其它请求参数组装
    if (queryBuilder != null)
        $.each(queryBuilder, function (i, n) {
            submitData[queryBuilder[i].name] = queryBuilder[i].value;
        });
        $.ajax({
            type: "post",
            dataType: "json",
            url: ashxParam.url,
            data: submitData,
            async: false,
            success: function (message) {
                total = message.totalCount;
                var data = message.data;
                if (_isClientColumns == false) {
                    columnInfo = message.Header;
                }
                pageIndex = parseInt(pageIndex);
                $("#contentTable tr").not($("#contentTable tr")[0]).remove();

                $("#contentTable").empty();

                //初始化表头部分
                if (columnInfo != null) {
                    var header = "";
                    if (isShowCheckBox == false) {
                        header = "<tr>";
                    } else {
                        header = "<tr ><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
                    }

                    if (browser.msie) {
                        if (isShowCheckBox == false) {
                            header = "<tr>";
                            //header = "<tbody><tr>";
                        }
                        else {
                            header = "<tbody><tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
                        }
                    }
                    var _i = 0;
                    if (_isClientColumns == false) {
                        _i = 1;
                    }
                    for (var i = _i; i < columnInfo.length; i++) {
                        if (columnInfo[i].width != undefined)
                            header += "<td class=\"headerTd\" width=\"" + columnInfo[i].width + "\">" + columnInfo[i].columnText + "</td>";
                        else
                            header += "<td class=\"headerTd\">" + columnInfo[i].columnText + "</td>";

                    }
                    header += "</tr>";
                    //if (browser.msie)
                    // header += "</body>";
                    $("#contentTable").append(header);
                }

                //    if (columnInfo != null) {
                //        $("#contentTable").empty();
                //        //初始化表头部分
                //        var header = "";
                //        header = "<tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
                //        if (browser.msie)
                //            header = "<tbody><tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
                //        for (var i = 0; i < columnInfo.length; i++) {
                //            if (columnInfo[i].width != undefined)
                //                header += "<td class=\"headerTd\" width=\"" + columnInfo[i].width + "\">" + columnInfo[i].columnText + "</td>";
                //            else
                //                header += "<td class=\"headerTd\">" + columnInfo[i].columnText + "</td>";

                //        }
                //        header += "</tr>"; //<td width=\"150px\" class=\"headerTd\">基本操作</td>
                //        if (browser.msie)
                //            header += "</body>";
                //        $("#contentTable").append(header);

                //    }
                if (total == null || data == null) {
                    //alert("没有符合条件的数据！！！");
                    $("#TB_load").remove();
                    return;
                }
                $.each(data, function (a, n) {
                    var row;
                    if (isShowCheckBox == false) {
                        row = "<tr onSelectStart=\"return false\" >";
                    }
                    else {
                        row = "<tr onSelectStart=\"return false\" ><td   width=\"50px\" class=\"contentTd_N\"><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";
                    }






                    var col = "";
                    var trId = ""//单一记录主键

                    //IE浏览器需要加上tbody标签，方能动态添加
                    if (browser.msie) {
                        if (isShowCheckBox == false) {
                            row = "<tr onSelectStart=\"return false\">";
                            //row = "<tbody><tr onSelectStart=\"return false\">";
                        }
                        else {
                            row = "<tbody><tr onSelectStart=\"return false\"><td  width=\"50px\" class=\"contentTd_N\"><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";
                        }
                    }
                    if (_isClientColumns == true) {
                        for (var i = 0; i < columnInfo.length; i++) {

                            col = columnInfo[i].columnName;
                            if (columnInfo[i].style != undefined)
                                row += "<td   >"
                            else
                                row += "<td  >";
                            if (n[col] == null)
                                row += "</td>";
                            else
                                row += n[col] + "</td>";
                        }
                    }
                    else {

                        var i = 1;


                        for (var result in n) {
                            if (i == 1) {
                                i++;
                                continue;
                            }
                            row += "<td  >";
                            if (n[result] == null)
                                row += "</td>";
                            else
                                row += n[result] + "</td>";
                        }

                    }
                    row += "</tr>";

                    //                    if (browser.msie)
                    //                        row += "</tbody>";

                    row = $(row);

                    for (var key in n) {
                        trId = n[key];
                        break;
                    }

                    row.attr("id", trId);

                    //行头的checkbox是否选中
                    if (isShowCheckBox != false) {
                        if ($.inArray(trId, selectRows) == -1)
                            row.find("input[type='checkbox']").prop("checked", false);
                        else
                            row.find("input[type='checkbox']").prop("checked", true);
                    }
                    row.unbind("dblclick");
                    if (fnDoubleClick != undefined && typeof fnDoubleClick == 'function') {
                        row.dblclick(fnDoubleClick);
                    } else {
                        row.dblclick(function () {
                            var recordId = row.attr("id");
                            popUpDetailPage(recordId, detailPage);

                        });
                    }




                    $("#contentTable").append(row);
                });



                if (total % pageSize == 0)
                    pageCount = total / pageSize;
                else
                    pageCount = parseInt(total / pageSize) + 1;


                $("#totalCountSpan").text(total);
                $("#pageIndexSpan").text(pageIndex + "/" + pageCount);
                $("#TB_load").remove();
                //行 背景色变色
                $("#contentTable tr").each(function () {
                    $tr = $(this);
                    var s = $(this).children("td").eq(colorColumnIndex).text();
                    //$tr.css("background-color", "#12FFC3");
                    this.setAttribute("style", "background-color:#12FFC3;height:25px;");
                    if (s == "7") {
                        //$tr.css("background-color", "#12FFC3");
                        this.setAttribute("style", "background-color:#12FFC3;height:25px;");
                    }
                    else if (s == "2") {
                        //$tr.css("background-color", "#FFF69A");
                        this.setAttribute("style", "background-color:#FFF69A;height:25px;");
                    }
//                    else if (s == "C") {
//                        //$tr.css("background-color", "#FDB66A");
//                        this.setAttribute("style", "background-color:#FDB66A;height:25px;");
//                    }
                    else  {
                        //$tr.css("background-color", "#FF8480");
                        this.setAttribute("style", "background-color:#FF8480;height:25px;");
                    }
                    
                });

                return false;
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#TB_load").remove();
                //alert(textStatus);
            }
        });
}

//分页按钮
function bindPageButton(isShowCheckBox, fnDoubleClick) {

    $("#firstBut").attr("href", "javascript:void(0)");
    $("#previousBut").attr("href", "javascript:void(0)");
    $("#nextBut").attr("href", "javascript:void(0)");
    $("#lastBut").attr("href", "javascript:void(0)");
    $("#gotoBut").attr("href", "javascript:void(0)");

    $("#firstBut").unbind("click");
    $("#previousBut").unbind("click");
    $("#nextBut").unbind("click");
    $("#lastBut").unbind("click");
    $("#gotoBut").unbind("click");

    //第一页
    $("#firstBut").click(function () {
        if (pageIndex != 1) {
            pageIndex = 1;
            pageClick(isShowCheckBox, fnDoubleClick, _colorColumnIndex);
        }
    });

    //上一页
    $("#previousBut").click(function () {
        if (pageIndex != 1) {
            pageIndex--;
            pageClick(isShowCheckBox, fnDoubleClick, _colorColumnIndex);
        }
    });


    //最后一页
    $("#lastBut").click(function () {
        if (pageIndex != pageCount) {
            pageIndex = pageCount;
            pageClick(isShowCheckBox, fnDoubleClick, _colorColumnIndex);
        }
    });


    //下一页
    $("#nextBut").click(function () {
        if (pageIndex != pageCount) {
            pageIndex++;
            pageClick(isShowCheckBox, fnDoubleClick, _colorColumnIndex);
        }
    });


    //跳转到
    $("#gotoBut").click(function () {
        var gotoPage = $("#pagerInput").val();

        var r = /^[0-9]*[1-9][0-9]*$///正整数 

        if (!r.test(gotoPage)) {
            alert("请输入合法数！！！");
            return false;
        }
        if (eval(gotoPage) < 1 || eval(gotoPage) > pageCount) {
            alert("页码超出范围！！！");
            return false;
        }

        var intGotoPage = parseInt(gotoPage);
        pageIndex = intGotoPage;
        pageClick(isShowCheckBox, fnDoubleClick, _colorColumnIndex);
        return false;
    });
}



/**
* 
*根据传入表单的ID及请求的服务地址执行表单提交工作,Action为01,执行添加操作
* 
*/
function InitAddPage(formId, ashxUrl) {
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },
        onValidationComplete: function (form, status) {
            if (status == true) {
                var formString = $("#" + formId).serialize() + "&action=01";
                if (SubmitFlag == true) {
                    ymPrompt.alert("请匆重复提交！", null, null, '警告', null);
                } else {
                    SubmitFlag == true;
                    $.ajax({
                        type: "post",
                        async: false,
                        data: formString,
                        dataType: "json",
                        url: ashxUrl,
                        success: function (message) {
                            SubmitFlag = false;
                            if (message.ISSucceed == false) {
                                ymPrompt.errorInfo('操作失败！' + message.Message, null, null, null, null);
                            } else {
                                ymPrompt.succeedInfo("添加成功！", null, null, null, autoClose)
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            SubmitFlag = false;
                            ymPrompt.errorInfo('操作失败！' + textStatus, null, null, null, null);
                        }
                    });
                }
            }
        }
    });
}


/**
* 
**根据传入的记录ID及请求参数（以JSON对像的形式）执行删除单条记录操作,Action为02。
* 
*/
function deleteRecord(ashxParam) {
    if (selectRows.length > 1) {
        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
        return false;
    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    if (SubmitFlag == true) {
        ymPrompt.alert("请匆重复提交！", null, null, '警告', null);
    } else {
        SubmitFlag == true;
        if (confirm('您确定要删除?')) {
            $.ajax({
                type: "post",
                async: false,
                data: { "id": selectRows[0], "action": "02" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    pageClick(_isShowCheckBox, _fnDoubleClick, _colorColumnIndex);
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                    selectRows = [];
                    SubmitFlag == false;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    SubmitFlag = false;
                    ymPrompt.errorInfo('操作失败！', null, null, null, null);
                }
            });
        }
    }
}

//关闭模态窗口
function autoClose() {
    window.parent.pageClick(_isShowCheckBox, _fnDoubleClick, _colorColumnIndex) ;
    window.parent.tb_remove();
}
/**
* 
*根据传入表单的ID及请求的服务地址执行表单提交工作,Action为03,执行修改操作。
* 
*/

function initEditPage(formId, ashxUrl) {
    var id = request("id");
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": "05" },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            var form = document.forms[formId];
            if (!jQuery.isPlainObject(data)) {
                data = data[0];
                //遍历指定form表单所有元素
                for (var i = 0; i < form.length; i++) {
                    var fieldName = form[i].name;
                    var prefix = fieldName.substr(0, 3).toLocaleLowerCase();
                    switch (prefix) {
                        case "tex": $("[name='" + fieldName + "']").val(data[fieldName.substr(3).toUpperCase()]); break;
                        case "hid": $("[name='" + fieldName + "']").val(data[fieldName.substr(3).toUpperCase()]); break;
                        case "sel": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3).toUpperCase()]); break;
                        case "rad": $("[name='" + fieldName + "'][value='" + data[fieldName.substr(3).toUpperCase()] + "']").prop("checked", true); break;
                        case "tet": $("textarea[name='" + fieldName + "']").val(data[fieldName.substr(3).toUpperCase()]); break;
                    }
                }
            } else {
                //遍历指定form表单所有元素
                for (var i = 0; i < form.length; i++) {
                    var fieldName = form[i].name;
                    var prefix = fieldName.substr(0, 3).toLocaleLowerCase();
                    switch (prefix) {
                        case "tex": $("[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                        case "hid": $("[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                        case "sel": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                        case "rad": $("[name='" + fieldName + "'][value='" + data[fieldName.substr(3)] + "']").prop("checked", true); break;
                        case "tet": $("textarea[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    }
                }
            }
            return data;
        }
        ,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ymPrompt.errorInfo('操作失败！', null, null, null, null);
        }
    });
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },

        onValidationComplete: function (form, status) {
            if (status == true) {
                var formString = $("#" + formId).serialize() + "&action=03&id=" + id;
                if (SubmitFlag == true) {
                    ymPrompt.alert("请匆重复提交！", null, null, '警告', null);
                } else {
                    SubmitFlag == true;
                    $.ajax({
                        type: "post",
                        async: false,
                        data: formString,
                        url: ashxUrl,
                        success: function (message) {
                            SubmitFlag = false;
                            if (message.ISSucceed == false) {
                                ymPrompt.errorInfo('操作失败！' + message.Message, null, null, null, null);
                            } else {
                                ymPrompt.succeedInfo("编辑成功！", null, null, null, autoClose)
                            }

                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            SubmitFlag = false;
                            ymPrompt.errorInfo('操作失败！', null, null, null, handler);
                        }
                    });
                }
            }
        }
    });
}

//使首字母大写
function replaceReg(str) {
    var reg = /\b(\w)|\s(\w)/g;
    str = str.toLowerCase();
    return str.replace(reg, function (m) { return m.toUpperCase() })
}
/**
* 
*根据传入表单的ID及请求服务地址初始化详细信息页面
* 
*/
function initDetailPage(formId, ashxUrl, detailAction) {
    var id = request("id");
    var detailaction = "05";
    if (detailAction != null && detailAction != undefined)
        detailaction = detailAction
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": detailaction },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            $("#" + formId + " label").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("id");
                var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                $("#" + fieldId).html(data[fieldId.substr(3)]);
            });

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ymPrompt.errorInfo('操作失败！', null, null, null, null);
        }
    });
}


/**
* 
**根据传入的记录ID，及详细页面的信息参数（JSON格式）跳出弹出框，用来查看该条记录的详细信息。
* 
*/
function popUpDetailPage(recordId, detailPage) {
    tb_show(detailPage.title, detailPage.url + "?id=" + recordId + "&keepThis=true&TB_iframe=true&height=" + detailPage.height + "&width=" + detailPage.width, false);
}



/**
* 
**根据传入的记录ID，及编辑页面的信息参数（JSON格式）跳出弹出框，用编辑页面。
* 
*/

function popUpEditPage(editPage) {

    if (selectRows.length > 1) {
        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
        return false;
    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择", null, null, null, null);
        return false;
    }

    tb_show(editPage.title, editPage.url + "?id=" + selectRows[0] + "&keepThis=true&TB_iframe=true&height=" + editPage.height + "&width=" + editPage.width, false);
}

//截取页面传递过来的URL参数
function request(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}


//初始化AutoComplete输入框，第一个参数为输入框的id，第二个参数为隐藏的取value值的id，第三个参数为ajax提交参数，第四个是取的JOSN数据的键
function initAutoComplete(textFieldInputId, valueFieldInputId, ajaxParam, itemParam) {
    var cache = {};

    $("#" + textFieldInputId).unbind("blur"); //失去输入焦点后，如果显示值为空，则同时清空隐藏值
    $("#" + textFieldInputId).bind("blur", function () {

        if ($("#" + textFieldInputId).val() == "") {
            $("#" + textFieldInputId).val("");
            $("#" + valueFieldInputId).val("");
        } else {
            if (($("#" + textFieldInputId).val() in cache) || $("#" + textFieldInputId).val().toString().length == 1)//如果是已经存在缓存中的关键字，也就是输入到文本框中的文字是不能提交的，只能选择后才能提交
            {
                $("#" + textFieldInputId).val("");
                $("#" + valueFieldInputId).val("");
            }
        }
    });

    $("#" + textFieldInputId).autocomplete({
        minLength: 2,
        autoFocus: true,
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response($.map(cache[term], function (item) {
                    return {
                        value: item[itemParam.textField],
                        label: item[itemParam.textField],
                        submitValue: item[itemParam.valueField]
                    }
                }));
                return;
            }
            ajaxParam.data.keywords = request.term;
            $.ajax({
                method: "post",
                url: ajaxParam.url,
                dataType: "json",
                data: ajaxParam.data,
                success: function (data) {
                    cache[term] = data;
                    response($.map(data, function (item) {
                        return {
                            value: item[itemParam.textField],
                            label: item[itemParam.textField],
                            submitValue: item[itemParam.valueField]
                        }
                    }));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        },
        select: function (e, ui) {
            $("#" + valueFieldInputId).val(ui.item.submitValue);
        }
    });
}


//初始化下拉框
function initDropDownList(selectId, ajaxParam, itemParam) {
    $.ajax({
        method: "post",
        async: false,
        url: ajaxParam.url,
        dataType: "json",
        data: ajaxParam.data,
        success: function (data) {
            $.each(data, function (i, n) {
                $("#" + selectId).append("<option value='" + n[itemParam.valueField] + "'>" + n[itemParam.textField] + "</option>");
            });
        }
    });
}


//初始化查询条件表单
function initQueryBuildForm(formId, __isShowCheckBox, __fnDoubleClick, arr) {
    $("#" + formId).submit(function (e) {
        pageIndex = 1; //初始化页面索引
        e.preventDefault();
        queryBuilder = $("#" + formId).serializeArray();
       
        initNewGrid(queryBuilder, ashxParam, addPage, editPage, detailPage, __isShowCheckBox, __fnDoubleClick, columnInfo, _colorColumnIndex);
        arr2 = new Array();
        if (arr != null && arr != undefined) {
            arr2 = arr.split(',');

            for (i = 0; i < arr2.length; i++) {
                table_rowspan("#contentTable", arr2[i]);
            }
        }
        return false;
    });
}
/**
* 
**根据传入的记录ID及请求参数（以JSON对像的形式）执行删除单条记录操作,Action为02。
* 
*/
function AuditRecord(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要审核选中的记录？', null, null, "审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "AuditRecord" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    if (result.ErrorCode == -998) {
                        alert("未回复的信息不能审核！！！");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

function RevocationRecord(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要撤销选中记录的审核？', null, null, "撤销审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "RevocationRecord" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

//推送信息
function PushRecords(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要推送选中的记录？', null, null, "推送提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "PushRecords" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    if (result.ErrorCode == -997) {
                        alert("已回复的信息不允许再推送！！！");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

function checkMaxInput(txt, maxLen) {
    if (txt.value.length > maxLen) // if too long.... trim it! 
        txt.value = txt.value.substring(0, maxLen); // otherwise, update 'characters left' counter 
    //else document.getElementById('remLen').innerText = maxLen - form.txtContent.value.length; 
}



function ShowRecord() {
    if (selectRows.length > 1) {
        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
        return false;
    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择", null, null, null, null);
        return false;
    }
    popUpDetailPage(selectRows[0], detailPage);
}

//审核诈骗信息
function SendZPXX(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要审核选中的记录？', null, null, "审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "ToExamine" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    if (data.ISSucceed == false) {
                        alert("审核失败！");
                    }
                    else {
                        alert("审核成功");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}
//设为常见问题
function SetCjwt(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要把该问题设为常见问题吗？', null, null, "审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "SetCjwt" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    if (data.ISSucceed == false) {
                        ymPrompt.alert("设置失败！");
                    }
                    else {
                        ymPrompt.alert("设置成功");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}
 